import 'package:app/api/material-pick/material.dart';
import 'package:app/components/index.dart';
import 'package:app/util/StringUtils.dart';
import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;

class ProductMaterialReturnDetail extends StatefulWidget {
  const ProductMaterialReturnDetail({
    super.key,
  });

  @override
  State<ProductMaterialReturnDetail> createState() =>
      _ProductMaterialReturnDetailState();
}

class MList {
  final String? itemCode;
  final String? itemName;
  final String? stockUnitName;
  late double reqQty;
  late double? maxQty;
  final String? seqNo;

  MList({
    this.itemCode,
    this.itemName,
    this.stockUnitName,
    required this.reqQty,
    this.maxQty,
    this.seqNo,
  });
  Map<String, dynamic> toJson() => {
    'itemCode': itemCode,
    'itemName': itemName,
    'stockUnitName': stockUnitName,
    'reqQty': reqQty,
    'seqNo': seqNo,
  };
  List<Map<String, dynamic>> toListJson(List<MList> list) {
    return list.map((item){
      return item.toJson();
    }).toList();
  }

}

class _ProductMaterialReturnDetailState
    extends State<ProductMaterialReturnDetail> {

  final FocusNode _firstFocusNode = FocusNode();
  // 退货单号
  String _erpInvBillCode = "";

  // 托盘号
  String _containerCode = "";

  // 位置
  String _station = "";

  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    // 在初始化时将焦点放在第一个文本框上
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
    });
  }

  /// 绑定物料
  void submit() {
    Forms.validate(_formKey!).then((valid) async {
      if (valid) {
        MaterialApi.of(context).bind({
          'container': _containerCode,
          'station': _station,
          'erpInvBillCode': _erpInvBillCode,
          'materialBackRows': _list
        }).then((res) {
          if (StringUtils.isNotNull(res.data)) {
            clear();
            Success.of(context).show('物料绑定成功');
          }
        });
      }
    });
  }

  void scan(String key) async{
    String? qrCode = await scanner.scan();
    if (key == 'station') {
      setState(() => _station = qrCode.toString());
    } else if (key == 'containerCode') {
      setState(() => _containerCode = qrCode.toString());
    } else if (key == 'erpInvBillCode') {
      setState(() => _erpInvBillCode = qrCode.toString());
    }
  }

  // 设置值
  void setValue(String key, String value) {
    switch (key) {
      case '_station':
        setState(() => _station = value);
        break;
      case '_containerCode':
        setState(() => _containerCode = value);
        break;
      case '_erpInvBillCode':
        setState(() => _erpInvBillCode = value);
        break;
      default:
        throw Exception("key error");
    }
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void clear() {
    setState(() {
      _station = '';
      _containerCode = '';
      _erpInvBillCode = '';
      _list = [];
    });
  }
  List<dynamic> _list = [];

  /// 确认
  void confirm() {
    MaterialApi.of(context).materialBacks(_erpInvBillCode).then((res) {
      if (StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)) {
        setState((){
          _list = res.data['data'].map((item){
            item['itemQty'] = 0 - double.parse(item['itemQty'].toString());
            item['maxQty'] = item['itemQty'];
            return item;
          }).toList();
        });
      }
    });
  }

  /// 添加数量
  void add(index) {
    final item = _list[index];
    double number = item['itemQty'] + 1;
    if(number.compareTo(item['maxQty'] as num) <= 0){
      setState(() {
        _list[index]['itemQty'] = number;
      });
    }
  }

  /// 减数量
  void subtraction(index) {
    final item = _list[index];
    double number = item['itemQty'] > 1 ? item['itemQty'] - 1 : 0;
    setState(() {
      _list[index]['itemQty'] = number;
    });
  }

  /// 删除
  void remove(index) {
    Confirm.of(context).show('确定要删除么？', () {
      setState(() {
        _list.removeAt(index);
      });
      Navigator.of(context).pop();
    });
  }

  /// 手动改变数量
  changeNumber(int index, String value){
      double val = value != '-' ? double.parse(value) : 0;
      if(val.compareTo(_list[index]['maxQty']) <= 0 && val > 1){
        setState(() {_list[index]['itemQty'] = val;
      });
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '物料绑定'),
      body: GestureDetector(
          onTap: hideKeyBorder,
          child: Column(
          children: [
            Group(
              // title: '站点号',
              context: context,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Forms(formKey: _formKey, formItem: [
                    FormItem(
                      onEntry: (String value) =>{confirm()},
                      type: 'input',
                      labelWidth: 90,
                      focusNode: _firstFocusNode,
                      labelText: '退库单号',
                      placeholder: '请扫退库单号',
                      filedName: 'erpInvBillCode',
                      value: _erpInvBillCode,
                      icon: const Icon(Icons.qr_code_scanner_rounded),
                      iconOnTap: () => scan('erpInvBillCode'),
                      onChange: (value) => setValue('_erpInvBillCode', value),
                      rules: const {'erpInvBillCode': [{'required': true, 'message': '退库单号不能为空'}]},
                    ),
                    FormItem(
                      type: 'input',
                      labelWidth: 90,
                      labelText: '站  点  码',
                      placeholder: '请扫站点号',
                      filedName: 'station',
                      value: _station,
                      icon: const Icon(Icons.qr_code_scanner_rounded),
                      iconOnTap: () => scan('station'),
                      onChange: (value) => setValue('_station', value),
                      rules: const {'station': [{'required': true, 'message': '站点码不能为空'}]},
                    ),
                    FormItem(
                      type: 'input',
                      labelWidth: 90,
                      labelText: '托  盘  码',
                      placeholder: '请扫托盘码',
                      filedName: 'containerCode',
                      value: _containerCode,
                      icon: const Icon(Icons.qr_code_scanner_rounded),
                      iconOnTap: () => scan('containerCode'),
                      onChange: (value) => setValue('_containerCode', value),
                      rules: const {'containerCode': [{'required': true, 'message': '托盘码不能为空'}]
                      },
                    ),

                  ]),
                  Padding(
                    padding:
                        const EdgeInsets.only(top: 10, right: 10, bottom: 10),
                    child:
                        Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                      Button(
                        label: '清空',
                        icon: Icons.delete_forever,
                        onPressed: clear,
                        fontColor: Colors.black,
                        backgroundColor: Colors.white,
                        borderColor: const Color.fromARGB(255, 133, 133, 133),
                      ),
                    ]),
                  ),
                ],
              ),
            ),
            Expanded(
              child: ListContainer(
                // title: '物料信息',
                length: _list.length,
                actions: [
                  SlidActions(
                    onPressed: remove,
                    label: '删除',
                    backgroundColor: Colors.red,
                    icon: Icons.delete,
                  )
                ],
                children: (index) {
                  return [
                    ListTitle(
                      context: context,
                      label: _list[index]['itemName'],
                    ),
                    Horizontal(items: [
                      HorizontalItem(
                        label: '物料编号：',
                        value: _list[index]['itemCode'],
                      ),
                      HorizontalItem(
                        label: '单位：',
                        value: _list[index]['itemUnit'],
                        fontColor: Colors.white,
                        valueBackground: const Color.fromARGB(255, 69, 228, 194),
                      )
                    ]),
                    Padding(
                      padding: const EdgeInsets.only(right: 5),
                      child: Number(
                        subtraction: ()=>{subtraction(index)},
                        add: ()=>{add(index)},
                        change: (String value)=>{changeNumber(index, value)},
                        value: _list[index]['itemQty'],
                      ),
                    ),
                  ];
                },
              ),
            ),
            SizedBox(
              width: MediaQuery.of(context).size.width,
              child: Padding(
                padding:
                    const EdgeInsets.only(top: 2, left: 20, right: 20, bottom: 5),
                child: Button(
                  onPressed: ()=>{submit()},
                  label: '绑定完成',
                  height: 60,
                  fontSize: 18,
                ),
              ),
            ),
          ],
      )),
    );
  }
}
